<template>
  <div class="main-chat-area">
    <!-- 1. 聊天头部区域 -->
    <div class="chat-header">
      <div class="header-info">
        <el-avatar 
          :size="40"
          :src="activeConversation?.avatar || 'https://ui-avatars.com/api/?name=默认&background=random'" 
          class="header-avatar"
        />
        <div class="header-details">
          <div class="chat-name">{{ activeConversation?.name || '未选择对话' }}</div>
          <div class="online-status" v-if="activeConversation?.isOnline">
            <span class="status-dot"></span> 在线
          </div>
        </div>
      </div>
    </div>

    <!-- 2. 消息列表区域 -->
    <div class="message-container">
      <div class="message-list">
        <div v-if="loading" class="loading-tip">加载中...</div>
        <div v-else-if="messages.length === 0" class="no-messages-tip">暂无消息</div>
        <!-- 消息项 - 区分自己和他人消息 -->
        <div 
          v-else
          v-for="(msg, index) in sortedMessages" 
          :key="index" 
          :class="['message-item', msg.isSelf ? 'self-message' : 'other-message']"
        >
          <!-- 他人消息头像（左侧） -->
          <el-avatar 
            v-if="!msg.isSelf" 
            :src="msg.sender_avatar" 
            class="message-avatar avatar-hover"
            @click="handleAvatarClick(msg)"
          />

          <!-- 自己消息头像（右侧） -->
          <el-avatar 
            v-if="msg.isSelf" 
            :src="userAvatar" 
            class="message-avatar avatar-hover"
            @click="handleAvatarClick(msg)"
          />

          <div class="message-content-wrapper">
            <div :class="['message-bubble', msg.isSelf ? 'self-bubble' : 'other-bubble']">
              <span class="message-text">{{ msg.content }}</span>
              <div :class="['message-time', msg.isSelf ? 'self-time' : '']">{{ formatDateTime(msg.time) }}</div>
            </div>
          </div>
          
          
        </div>
      </div>
    </div>

    <!-- 3. 输入区域 -->
    <div class="input-area">
      <div class="input-tools">
        <button class="tool-btn" @mouseenter="showToolTip($event, '表情')" @mouseleave="hideToolTip">
          <i class="el-icon-smile"></i>
        </button>
        <button class="tool-btn" @mouseenter="showToolTip($event, '图片')" @mouseleave="hideToolTip">
          <i class="el-icon-picture"></i>
        </button>
        <button class="tool-btn" @mouseenter="showToolTip($event, '文件')" @mouseleave="hideToolTip">
          <i class="el-icon-document"></i>
        </button>
        
        <!-- 工具提示 -->
        <div 
          class="tool-tooltip" 
          v-if="tooltipText"
          :style="{ left: tooltipX + 'px', top: tooltipY + 'px' }"
        >
          {{ tooltipText }}
        </div>
      </div>
      
      <textarea 
        v-model="inputMessage" 
        placeholder="输入消息..."
        class="message-input"
        @keydown.enter.prevent="handleEnter"
      ></textarea>
      
      <button 
        @click="sendMessage" 
        class="send-btn"
        :disabled="!inputMessage.trim()"
      >
        发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, computed, onUnmounted } from 'vue'
import { defineProps } from 'vue'
import { defineEmits } from 'vue'
import { formatDateTime } from '@/utils/timeUtils'
import chatApi from '@/api/chat'
import { ElMessage } from 'element-plus'


// 定义 props
const props = defineProps({
  activeConversation: {
    type: Object,
    default: null
  }
})

// 定义emits(向外传递数据)
const emit = defineEmits(['avatar-click'])

// 响应式数据
const inputMessage = ref('')
const userAvatar = ref('https://ui-avatars.com/api/?name=我&background=random&color=fff')
const messages = ref([])
const sentUserId = ref()
const tooltipText = ref('')
const tooltipX = ref(0)
const tooltipY = ref(0)
const loading = ref(false)
const userInfo = ref(JSON.parse(localStorage.getItem('user_info')) || {})

// 定时器
let messagesRefreshTimer = null

// 计算属性：按时间排序的消息列表
const sortedMessages = computed(() => {
  return [...messages.value].sort((a, b) => a.timestamp - b.timestamp)
})

// 处理头像点击事件
const handleAvatarClick = (message) => {
  console.log('点击了头像，消息内容：', message)
  emit('avatar-click', {
    type: 1,
    name: message.sender_name,
    email: message.sender_email,
    id: message.sender_id,
    phone: message.sender_phone,
    avatar: message.sender_avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(message.name)}&background=random`,
    user_id: message.sender_user_id,
  })
}
// 发送消息方法
const sendMessage = async () => {
  if (!inputMessage.value.trim() || !props.activeConversation) return

  try {
    // 确定接收者类型和ID
    let receiverType, receiverId
    
    // 根据会话类型确定参数
    if (props.activeConversation.type === 'contacts' || props.activeConversation.type === 1 ) {
      // 单聊
      receiverType = 1
      receiverId = props.activeConversation.id
    } else if (props.activeConversation.type === 'groups' || props.activeConversation.receiver_type === 2 ) {
      // 群聊
      receiverType = 2
      receiverId = props.activeConversation.id
    } else {
      // 默认情况
      receiverType = 1
      receiverId = props.activeConversation.id
    }
    
    // 调用API发送消息
    const response = await chatApi.sendMessage({
      receiver_id: receiverId,
      content_type: 1, // 文本消息
      content: inputMessage.value,
      receiver_type: receiverType
    })
    
    // 添加到消息列表
    const newMessage = {
      id: response.message_id,
      content: inputMessage.value,
      timestamp: Date.now(),
      time: new Date().toISOString().slice(0, 19).replace('T', ' '),
      isSelf: true,
      fromAvatar: userInfo.value.avatar || userAvatar.value
    }
    
    messages.value.push(newMessage)
    inputMessage.value = ''
    
    // 滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.message-container')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

// 处理回车发送（Ctrl+Enter换行）
const handleEnter = (e) => {
  if (e.ctrlKey) {
    inputMessage.value += '\n'
  } else {
    sendMessage()
  }
}

// 显示工具提示
const showToolTip = (e, text) => {
  tooltipText.value = text
  tooltipX.value = e.target.getBoundingClientRect().left + e.target.offsetWidth / 2 - 20
  tooltipY.value = e.target.getBoundingClientRect().top - 30
}

// 隐藏工具提示
const hideToolTip = () => {
  tooltipText.value = ''
}

// 加载历史记录
const loadHistoryMessages = async (conversation) => { 
  if (!conversation) return

  loading.value = true
  try {
    // 确定接收者类型和ID
    let receiverType, receiverId
    
    // 根据会话类型确定参数
    if (conversation.receiver_type === 1) {
      // 单聊
      receiverType = 1
      receiverId = conversation.id
    } else if (conversation.receiver_type === 2) {
      // 群聊
      receiverType = 2
      receiverId = conversation.id
    } else {
      // 默认情况
      receiverType = 1
      receiverId = conversation.id
    }

    const response = await chatApi.getChatHistory({
      receiver_type: receiverType,
      receiver_id: receiverId,
      page: 1,
      page_size: 20
    })

    console.log('历史消息数据:', response)
    if (response && response.messages) {
      // 处理消息数据，区分自己发送的消息和他人发送的消息
      messages.value = response.messages.map(msg => {
        const isSelf = msg.sender_id === userInfo.value.id
        console.log('message', msg)
        return {
          id: msg.id,
          content: msg.content,
          time: msg.created_at,
          timestamp: msg.timestamp,
          sender_avatar: msg.sender_avatar,
          sender_name: msg.sender_name,
          sender_email: msg.sender_email,
          sender_id: msg.sender_id,
          sender_user_id: msg.sender_user_id,
          sender_phone: msg.sender_phone,
          isSelf: isSelf,
          fromAvatar: isSelf 
            ? (userInfo.value.avatar || userAvatar.value)
            : (conversation.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(conversation.name)}&background=random`)
        }
      })
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    ElMessage.error('加载历史消息失败')
  } finally {
    loading.value = false
    // 滚动到页面底部
    scrollToBottom()
  }
}

// 监听会话切换
watch(
  () => props.activeConversation,
  (newVal) => {
    if (newVal) {
      // 先将先前的ID清空
      sentUserId.value = null
      sentUserId.value = newVal.id
      // console.log('当前会话已切换:', newVal)
      // 清空消息列表
      messages.value = []
      // 加载历史记录
      loadHistoryMessages(newVal)

      // 重置消息刷新定时器
      if (messagesRefreshTimer) {
        clearInterval(messagesRefreshTimer)
      }
      // 设置历史消息5秒自动刷新
      messagesRefreshTimer = setInterval(() => {
        if (newVal) {
          loadHistoryMessages(newVal)
        }
      }, 5000)
    } else {
      // 清空消息列表
      messages.value = []
      // 清除定时器
      if (messagesRefreshTimer) {
        clearInterval(messagesRefreshTimer)
      }
    }
  },
  { immediate: true }
)

// 组件卸载时清除定时器
onUnmounted(() => {
  if (messagesRefreshTimer) {
    clearInterval(messagesRefreshTimer)
  }
})
</script>

<style scoped>
/* 主容器样式 */
.main-chat-area {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f9fc;
  overflow: hidden;
}

/* 头部样式 */
.chat-header {
  padding: 0 16px;
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.header-info {
  display: flex;
  align-items: center;
}

.header-avatar {
  transition: transform 0.2s ease;
  cursor: pointer;
}

.header-avatar:hover {
  transform: scale(1.05);
}

.header-details {
  margin-left: 12px;
}

.chat-name {
  font-weight: 500;
  color: #333;
}

.online-status {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  margin-top: 3px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #00b42a;
  margin-right: 4px;
}

/* 消息区域样式 */
.message-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.loading-tip, .no-messages-tip {
  text-align: center;
  color: #999;
  font-size: 14px;
  margin-top: 20px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  align-items: flex-end;
  animation: fadeIn 0.3s ease forwards;
  opacity: 0;
}

.other-message {
  align-self: flex-start;
  align-items: flex-start;
}

.self-message {
  align-self: flex-end;
  flex-direction: row-reverse;
  align-items: flex-start;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 8px;
}

.avatar-hover {
  transition: all 0.2s ease;
  cursor: pointer;
}

.avatar-hover:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.message-content-wrapper {
  max-width: 70%;
  align-self: flex-start;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 12px;
  position: relative;
  word-wrap: break-word;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.message-bubble:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.other-bubble {
  background-color: #fff;
  border-top-left-radius: 4px;
}

.self-bubble {
  background-color: #409eff;
  color: #fff;
  border-top-right-radius: 4px;
}

.message-time {
  font-size: 11px;
  margin-top: 4px;
  opacity: 0.8;
  text-align: left;
}

.self-time {
  text-align: right;
}

/* 输入区域样式 */
.input-area {
  padding: 12px 16px;
  border-top: 1px solid #eee;
  background-color: #fff;
  flex-shrink: 0;
}

.input-tools {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  position: relative;
}

.tool-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background-color: #f5f5f5;
  color: #666;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.tool-btn:hover {
  background-color: #e8f3ff;
  color: #409eff;
  transform: translateY(-2px);
}

.tool-tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  pointer-events: none;
  animation: tooltipFade 0.2s ease;
  z-index: 10;
}

.tool-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border-width: 4px;
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.7) transparent transparent transparent;
}

.message-input {
  width: 100%;
  min-height: 60px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  max-height: 150px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.message-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  outline: none;
}

.send-btn {
  margin-top: 10px;
  padding: 8px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  float: right;
}

.send-btn:hover:not(:disabled) {
  background-color: #3688e8;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(64, 158, 255, 0.3);
}

.send-btn:active:not(:disabled) {
  transform: translateY(0);
}

.send-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes tooltipFade {
  from {
    opacity: 0;
    transform: translateY(5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .message-content-wrapper {
    max-width: 85%;
  }
}
</style>